package hub.cathome.controller;

import com.alibaba.druid.sql.visitor.functions.Char;
import hub.annotation.Affairs;
import hub.annotation.View;
import hub.cathome.entity.ResourceLink;
import hub.cathome.entity.ShotBlog;
import hub.cathome.entity.User;
import hub.cathome.entity.tool.ApplicationProperties;
import hub.cathome.service.HashPassword;
import hub.cathome.service.ResourceService;
import hub.cathome.service.ShotBlogService;
import hub.cathome.service.UserService;
import hub.cathome.service.impl.HashPasswordService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
@SessionAttributes(names={"user"},types = {User.class})
public class UserController {
    @Resource(name="userService")
    private UserService userService;
    @Resource(name="shotBlogService")
    private ShotBlogService shotBlogService;
    @Resource(name="resourceService")
    private ResourceService resourceService;
    @Resource(name="hashPassword")
    private HashPassword hashPassword;
    /**
     * 该视图传递的数据包括， user,shotBlogList，分别为用户信息和用户所有的随拍信息
     * **/
    @View("用户信息视图")
    @GetMapping("/home")
    public String userHome(Model model, HttpSession session){
        User user = (User) session.getAttribute("user");
        System.out.println(user);
        if(user==null){
            System.out.println("登陆失败");
            return "/home/login";
        }
        List<ShotBlog> shotBlogList = shotBlogService.getShotBlogByUserId(user.getId());
        model.addAttribute("userShotBlogList",shotBlogList);
        return "home/home";
    }
    @View("用户信息编辑视图")
    @GetMapping("/home/edit")
    public String editUserInformation(){
        return "home/edit";
    }
    @Affairs("保存更新的用户信息")
    @RequestMapping("/affair/save/{userId}")
    public String saveUserInformation(@RequestParam("image") MultipartFile file,@RequestParam("nickname") String nickname,@RequestParam("password") String password,@RequestParam("gender") String gender, Model model, @PathVariable Integer userId, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        List<ResourceLink> resourceLinks = resourceService.getResourceLinkByUserId(user.getId());
        for(ResourceLink resourceLink:resourceLinks){
            resourceService.deleteResourceLink(resourceLink.getResourceId());
        }
        user.setNickname(nickname);
        int count = userService.getUserCountByComplexName(nickname);
        if(count>1){
            model.addAttribute("error","已经有重复的用户名或昵称了");
            return "error/error";
        }
        if(count==1){
            User ut = userService.getUserByComplexName(nickname);
            if(!Objects.equals(ut.getId(), user.getId())){
                model.addAttribute("error","已经有重复的用户名或昵称了");
                return "error/error";
            }
        }
        Long hashedPassword = hashPassword.createKey(password);
        user.setPassword(hashedPassword);
        user.setGender(gender);
        String fileName = file.getOriginalFilename();
        String extName = StringUtils.getFilenameExtension(fileName);
        String targetName = UUID.randomUUID()+"."+extName;
        ResourceLink resourceLink = new ResourceLink();
        resourceLink.setDate(new Date());
        resourceLink.setPath(targetName);
        resourceLink.setType(3);
        resourceLink.setForId(user.getId());
        resourceService.insertResourceLink(resourceLink);
        userService.updateUser(user);
        User u2 = userService.getUserByUserId(user.getId());
        model.addAttribute("user",u2);
        String absoluteLocalPath = ApplicationProperties.getAbsoluteLocalPath(targetName);
        String prePath = absoluteLocalPath.substring(0,absoluteLocalPath.lastIndexOf(File.separator));
        if(!new File(prePath).exists()){
            boolean success = new File(prePath).mkdirs();
            if(!success){
                return "error/error";
            }
        }
        try {
            file.transferTo(new File(absoluteLocalPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "home/home";
    }
    @Affairs("注销用户并注销登录")
    @RequestMapping("home/delete")
    public String deleteUserInformation(HttpSession session, SessionStatus sessionStatus){
        User user = (User) session.getAttribute("user");
        final Integer id = user.getId();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                userService.deleteUser(id);
            }
        });
        thread.start();
        sessionStatus.setComplete();
        return "redirect:index";
    }
}
